package com.example.xmlparsedemo

import android.nfc.Tag
import android.text.TextUtils
import android.util.Log
import org.xml.sax.Attributes
import org.xml.sax.helpers.DefaultHandler

class SAXHelper : DefaultHandler() {
    companion object {
        const val TAG = "SAXHelper"
    }

    private var strBuffer: StringBuffer? = null
    private var mWxAccounts: MutableList<WxAccountBean>? = null
    private var mWxAccountBean: WxAccountBean? = null
    private var mTagName: String? = ""

    override fun startDocument() {
        super.startDocument()
        Log.e(TAG, "开始解析")
    }

    override fun endDocument() {
        super.endDocument()
        Log.e(TAG, "结束解析")
    }

    override fun startElement(
        uri: String?,
        localName: String?,
        qName: String?,
        attributes: Attributes?
    ) {
        super.startElement(uri, localName, qName, attributes)
        //localName==>标签名
        //attributes==>属性数组
        Log.e(TAG, localName ?: "unknown")
        strBuffer = StringBuffer()
        if (TextUtils.equals(localName, "WxAccounts")) {
            mWxAccounts = arrayListOf()
        }
        if (TextUtils.equals(localName, "WxAccount")) {
            mWxAccountBean = WxAccountBean()
        }
        mTagName = localName

    }

    override fun endElement(uri: String?, localName: String?, qName: String?) {
        super.endElement(uri, localName, qName)
        Log.e(TAG, localName ?: "unknown")
        if (TextUtils.equals(localName, "WxAccount")) {
            if (mWxAccountBean != null) {
                mWxAccounts?.add(mWxAccountBean!!)
            }
            mWxAccountBean = null
        }
    }

    override fun characters(ch: CharArray?, start: Int, length: Int) {
        var string = String(ch ?: CharArray(0), start, length)
        when (mTagName) {
            "name" -> {
                strBuffer?.append(string)
                mWxAccountBean?.name = strBuffer.toString()
            }
            "sex" -> {
                strBuffer?.append(string)
                mWxAccountBean?.sex = strBuffer.toString()
            }
        }
    }

    fun getList(): MutableList<WxAccountBean>? {
        return mWxAccounts
    }
}